import dayjs from "dayjs";
importClass('android.view.WindowManager');
importClass("android.view.Gravity");
importClass("android.graphics.PixelFormat");
declare const WindowManager: any;
import { getLiveRoomInfo } from "./v3/getLiveRoomInfo";
import { getRedPacketInfo } from "./v3/getRedPacketInfo";
import { getSafeClip } from "./v3/getSafeClip";
import { clearDialog } from "./v3/clearDialog";
import { FloatyWindow } from "floaty";
import { View } from "ui";
import { Thread } from "threads";

auto.waitFor();
const config = storages.create(`com.sker.auto`)
const emitter = events.emitter()
let sleepTime: number = 0;
let packagename: string = `com.smile.gifmaker`;
let total: number = 0;
let success: number = 0;
let fail: number = 0;
let isDev: boolean = false;
let allThreads: Thread[] = [];
let window: FloatyWindow & {
    [prop: string]: View;
};

runThread(1000 * 60 * 60);

function runThread(timeout: number) {
    render()
    const thread = threads.start(() => {
        while (getCurrentPackage() === packagename) {
            back();
            sleep(3000)
            clearDialog();
            if (selector().descMatches(/首页|精选|消息|我/).findOne(1000 * 10)) {
                home();
            }
        }
        while (true) {
            if (isSleep()) {
                while (getCurrentPackage() === packagename) {
                    back();
                    sleep(3000)
                    clearDialog();
                    if (selector().descMatches(/首页|精选|消息|我/).findOne(1000 * 10)) {
                        home();
                    }
                }
            }
            while (isSleep()) {
                sleepTime += 1;
                updateFloat({ toast: `夜间休息${formatMinute(sleepTime)}`, tip: ``, currentTask: `夜间休息`, currentResult: formatMinute(sleepTime) })
                sleep(1000)
            }
            run();
        }
    })
    allThreads.push(thread)
}


function getLinkPkg() {
    return httpPost(`getLinkPkg`, { type: '口令', uuid: config.get("DEVICE_UUID") })
}

function joinRedPack() { 

}

function run() {
    try {
        // 获取下一个链接
        const redPackets = getLinkPkg()
        if (redPackets && redPackets.length > 0) {
            
        }
        // total += 1;
        // updateFloat({ total: `${total}`, currentTask: `抢包`, toast: `正在进行抢包...`, currentResult: `第${total}个` })
        // clearDialog();
        // const liveRoomInfo = getLiveRoomInfo()
        // if (liveRoomInfo) {
        //     safeRun(() => liveRoomInfo?.open())
        //     sleep(3000)
        //     // 有红包
        //     const redPacketInfo = getRedPacketInfo()
        //     sleep(1000)
        //     safeRun(() => redPacketInfo?.close())
        //     const redPackets = redPacketInfo.redPackets?.filter(red => {
        //         if (red.type === '口令') {
        //             return true;
        //         }
        //         return false;
        //     });
        //     if (redPackets && redPackets.length > 0) {
        //         // 参加红包 等待开奖
        //         const redPacket = redPackets[0];
        //         redPacket.join()
        //         sleep(1000)
        //         const send = selector().textContains('发送').visibleToUser(true).findOne(1000 * 5);
        //         if (send) {
        //             clickButton(send)
        //             // 参加成功 等待开奖
        //             new WaitRedOpenAction().run();
        //         } else {
        //             clearDialog();
        //         }
        //     }
        // }
    } catch (e) {
        fail += 1;
        updateFloat({ fail: `${success}`, tip: `${dayjs().format('HH:mm:ss')} ${e.message}` })
        clearDialog();
        sleep(1000)
    } finally {
        clearDialog();
        sleep(1000)
    }
}

const interval = setInterval(() => { }, 1000 * 30)
events.on('exit', () => {
    if (allThreads && allThreads.length > 0) {
        allThreads.map(thread => {
            if (thread.isAlive()) {
                thread.interrupt()
            }
        })
    }
    if (interval) clearInterval(interval)
    safeRun(() => emitter.removeAllListeners())
    safeRun(() => window && window.exitOnClose())
    safeRun(() => config.remove('MINE_TASK'))
})


class WaitRedOpenAction {
    run() {
        selector().textMatches(/.*?秒后开奖/).waitFor()
        let node = selector().textMatches(/.*?秒后开奖/).findOne()
        const text = node.text();
        let total = 0;
        if (text) {
            const res = text.match(/(\d+)秒后开奖/)
            if (res && res.length > 0) {
                let [, time] = res;
                console.log({ time })
                total = parseInt(time);
            }
        }
        while (total > 0) {
            total -= 1;
            updateFloat({ currentResult: `等待开奖${total}s` })
            sleep(1000)
        }
        let leave = 10;
        while (leave > 0) {
            leave -= 1;
            updateFloat({ currentResult: `${leave}s后离开直播间` })
            sleep(1000)
        }
        /**
         * todo 查询中i将结果
         */
        return true;
    }
}
function safeRun(fn: Function) {
    try {
        fn()
        return true;
    } catch (e) {
        return false;
    }
}

function clickButton(btn: UiObject) {
    if (!btn) return false;
    if (btn.clickable()) {
        return btn?.click()
    } else {
        const bounds = btn.bounds();
        click(bounds.centerX(), bounds.centerY());
        return true;
    }
}


function formatNumber(val: number) {
    if (val < 10) return `0${val}`
    return `${val}`
}
function formatMinute(value: number) {
    if (value <= 0) return `00:00`
    value = parseInt(`${value}`)
    const minute = Math.floor(value / 60)
    const second = value % 60;
    return `${formatNumber(minute)}:${formatNumber(second)}`
}
function isSleep() {
    if (isDev) return false;
    const now = dayjs()
    const hour = now.get('hour')
    if (hour >= 23) {
        // 休息
        return true;
    }
    if (hour < 8) {
        // 休息
        return true;
    }
    return false;
}
function getCurrentPackage() {
    return selector().visibleToUser(true).findOne()?.packageName()
}
const httpPost = (path: string, body: object) => {
    const host = `60.204.248.43`
    const port = 3102
    let url: string = path;
    if (!url.startsWith(`http`)) {
        url = `http://${host}:${port}/autojs/core/autox/${path}`
    }
    const res = http.post(url, body, {
        timeout: 5 * 1000,
        contentType: 'application/json'
    })
    if (res.statusCode !== 200) {
        throw new Error(`请求失败`);
    }
    if (res.headers["Content-Type"].includes('text/html')) {
        throw new Error(`请求失败ContentType类型有误`);
    }
    const resData: any = res.body.json();
    const { success, message, data } = resData;
    if (success) {
        return data;
    } else {
        throw new Error(message)
    }
}

function render(): void {
    if (!floaty.checkPermission()) {
        floaty.requestPermission();
    }
    floaty.closeAll()
    window = floaty.window(`<frame id="main" w="*" h="*" bg="#000000" alpha="0">
    <vertical w="*" h="*">
        <horizontal padding="0 0 0 0">
            <text w="*" padding="15 5 15 5" bg="#130B2E" h="auto" id="toast" textSize="16" gravity="center" text="" textColor="#D12E2E"/>
        </horizontal>
        <horizontal padding="15 5 15 5">
            <text w="auto" textSize="12" gravity="left" text="当前任务：" textColor="#E2E1CF"/>
            <text w="*" id="currentTask" textSize="14" gravity="left" text="-" textColor="#f29a8c"/>
        </horizontal>
        <horizontal padding="15 5 15 5">
            <text w="auto" textSize="12" gravity="left" text="执行结果：" textColor="#F2F2F2"/>
            <text w="*" id="currentResult" textSize="14" gravity="left" text="-" textColor="#f29a8c"/>
        </horizontal>
        <horizontal padding="15 5 15 5">
            <horizontal layout_weight="1">
                <text w="auto" textSize="12" gravity="left" text="快手：" textColor="#F2F2F2"/>
                <text w="*" id="kwaiCurrentMoney" textSize="14" gravity="left" text="-" textColor="#E2E1CF"/>
            </horizontal>
            <horizontal layout_weight="1">
                <text w="auto" textSize="12" gravity="left" text="分配" textColor="#F2F2F2"/>
                <text w="*" id="kwaiTodayCount" textSize="14" gravity="left" text="-" textColor="#E2E1CF"/>
            </horizontal>
            <horizontal layout_weight="1">
                <text w="auto" textSize="12" gravity="left" text="快币：" textColor="#F2F2F2"/>
                <text w="*" id="kwaiTodayMoney" textSize="14" gravity="left" text="-" textColor="#E2E1CF"/>
            </horizontal>
        </horizontal>
        <horizontal padding="15 5 15 5">
            <horizontal layout_weight="1">
                <text w="auto" textSize="12" gravity="left" text="极速：" textColor="#F2F2F2"/>
                <text w="*" id="nebulaCurrentMoney" textSize="14" gravity="left" text="-" textColor="#E2E1CF"/>
            </horizontal>
            <horizontal layout_weight="1">
                <text w="auto" textSize="12" gravity="left" text="分配" textColor="#F2F2F2"/>
                <text w="*" id="nebulaTodayCount" textSize="14" gravity="left" text="-" textColor="#E2E1CF"/>
            </horizontal>
            <horizontal layout_weight="1">
                <text w="auto" textSize="12" gravity="left" text="快币：" textColor="#F2F2F2"/>
                <text w="*" id="nebulaTodayMoney" textSize="14" gravity="left" text="-" textColor="#E2E1CF"/>
            </horizontal>
        </horizontal>
        <horizontal padding="15 5 15 5">
            <text w="*" id="tip" textSize="12" gravity="center" text="-" textColor="#f29a8c"/>
        </horizontal>
    </vertical>
</frame>`)
    const uitask = threads.start(() => {
        ui.run(() => {
            const parentParent = window.main.parent.parent.parent;
            let params = parentParent.layoutParams || {};
            if (params.flags == 16777736) {
                log("当前可以触摸, 修改为不可触摸");
                params.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
            } else if (params.flags == 16777752) {
                log("当前不可以触摸, 修改为可触摸");
                params.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
            }
            const windowManager = context.getSystemService(context.WINDOW_SERVICE);
            windowManager.updateViewLayout(parentParent, params);
            const w = window;
            let wh = w.getHeight();
            let dw = device.width;
            let dh = device.height;
            w.setSize(dw + 100, wh);
            w.main.attr('alpha', .9)
            // 悬浮窗置于底部中央
            let y = dh - wh;
            w.setPosition(0, y);
        })
    })
    uitask.waitFor()
    uitask.join()
    uitask.interrupt()
    const updateUi = (state: any) => {
        ui.run(() => {
            Object.keys(state).map(key => {
                const val = state[key]
                window.findView(key)?.setText(`${val}`)
            })
        })
    }
    emitter.on('UPDATE_FLOAT_WINDOW_STATE_CHANGE', (val: any) => {
        const storage: any = config.get(`MINE_TASK`, {});
        const state = {
            currentTask: '抓包',
            ...storage,
            ...val,
        };
        config.put(`MINE_TASK`, state)
        updateUi(state)
    });
}

function updateFloat(data: { currentTask?: string, currentResult?: string, tip?: string, toast?: string, success?: string, fail?: string, total?: string }) {
    emitter.emit('UPDATE_FLOAT_WINDOW_STATE_CHANGE', data)
}

function openKsLive(signal: boolean = true) {
    let flag: any = signal ? Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK : Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
    const uri = `kwai://liveaggregatesquare`
    const intent = app.intent({
        action: "android.intent.action.VIEW",
        data: uri,
        flags: flag
    });
    context.startActivity(intent);
}